<?php 

class Helper_Valid extends Zend_Controller_Action_Helper_Abstract {
	
	/**
	 * Kontrola operacji na obiekcie
	 */
	
	private $validator = null;
	
	public function direct(My_Model $table,$type=Enum_Operations::SAVE){
		$testing = $this->operate($table,$type);
		if($testing!==true){
			if(is_array($testing)){
				die(json_encode(array("success"=>false,"msg"=>$testing['msg'],"rows"=>array(),"window"=>array(
					'title'=>$testing['title'],
					'obstacles'=>$testing['obstacles']
				))));
			} else die(json_encode(array("success"=>false,"msg"=>$testing,"rows"=>array())));
		} else {
			if(is_object($this->validator)){
				$valid = $this->validator;
		
				if(property_exists($valid, '_finish') && array_key_exists($type,$valid->_finish)){
					$method = $valid->_finish[$type];
					$v = new stdClass();
					$v->validator = $valid;
					$v->methodName = $method;
					return $v;// obiekt jest zawsze boolean true - (od php 5) 
				}
			}
			return true;
		}
	}
	
	public function operate($table,$type){
	
		if( method_exists($table, 'getValidator') && ($valid = $table->getValidator())){
								
			$this->validator = $valid;
			
			if(property_exists($valid, '_prepare') && array_key_exists($type,$valid->_prepare)){
				$method = $valid->_prepare[$type];
				$valid->$method();
			}
			if(property_exists($valid, '_tests') && array_key_exists($type,$valid->_tests)){
				foreach($valid->_tests[$type] as $test){
					if(($result = $valid->$test())!==true){
						return $result;
					}
				}
				return true;
			} else return true;
		} else return true;
	}
	
	public function fin($finisher){
		if(is_object($finisher)){
    		$method = $finisher->methodName;
    		$finisher->validator->$method();
    	}
	}
	
}

?>